//
//  ZJAudioPlayer.m
//  SoundRecording
//
//  Created by zhengju on 2017/12/2.
//  Copyright © 2017年 郑俱. All rights reserved.
//

#import "ZJAudioPlayer.h"

@interface ZJAudioPlayer()<NSCopying,NSMutableCopying,AVAudioPlayerDelegate>
@property(strong,nonatomic) NSURL * recorderUrl;
@property(strong,nonatomic) AVAudioPlayer * audioPlayer;
@end



@implementation ZJAudioPlayer
+ (instancetype)sharePlayer{
    static  ZJAudioPlayer * player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[super allocWithZone:NULL]init];
    });
    return player;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
    return [ZJAudioPlayer sharePlayer];
}
- (id)copyWithZone:(NSZone *)zone{
    return [ZJAudioPlayer sharePlayer];
}
- (id)mutableCopyWithZone:(NSZone *)zone{
    return [ZJAudioPlayer sharePlayer];
}
- (NSURL *)getRecordAudioPath:(NSString *)urlPath{
    NSURL *url=[NSURL fileURLWithPath:urlPath];
    return url;
}
- (void)recorderSetPath:(NSString *)urlPath{
    self.recorderUrl = [self getRecordAudioPath:urlPath];
}
/**
 *  创建播放器
 *
 *  @return 播放器
 */
-(AVAudioPlayer *)audioPlayer{
    
    NSURL *url = self.recorderUrl;
    NSError *error=nil;
    _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
    _audioPlayer.numberOfLoops=0;
    [_audioPlayer prepareToPlay];
    _audioPlayer.delegate = self;
    _audioPlayer.volume = 0.8;//0.0~1.0之间
    if (error) {
        NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
        return nil;
    }
    
    return _audioPlayer;
}
- (void)recorderPlay{
    if ([self.audioPlayer isPlaying]) {
        [self.audioPlayer stop];
        
    }else{
        
    }
    [self.audioPlayer play];
}
#pragma mark --AVAudioPlayerDelegate
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"player 播放失败%@",error);
    
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"player:%@ 播放完成%d",player,flag);
    //    //根据实际情况播放完成可以将会话关闭，其他音频应用继续播放
    [[AVAudioSession sharedInstance]setActive:NO error:nil];
    AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
    
    
}
@end
